package com.emapp.lccode.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.location.Location
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.lifecycle.viewModelScope
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.afollestad.materialdialogs.list.listItems
import com.amap.api.location.AMapLocationClient
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.PolygonOptions
import com.amap.api.maps.model.Polyline
import com.amap.api.maps.model.PolylineOptions
import com.amap.api.services.core.AMapException
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeResult
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.emapp.lccode.R
import com.emapp.lccode.base.BaseActivity1
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.bean.DeviceKt
import com.emapp.lccode.bean.SelectType
import com.emapp.lccode.bean.UpLatLngKt
import com.emapp.lccode.databinding.ActivityProjectMapBinding
import com.emapp.lccode.mode.ProjectViewModel
import com.emapp.lccode.utils.MapAppUtil
import com.emapp.lccode.utils.MmkvUtil
import com.emapp.lccode.utils.SettingUtil
import com.emapp.lccode.utils.getIconByNameState
import com.emapp.lccode.utils.getLuByNameState
import com.emapp.lccode.utils.getluJsonString
import com.emapp.lccode.utils.scaleBitmap
import com.emapp.lccode.utils.setOnclickNoRepeat
import com.emapp.lccode.utils.showInfo
import com.emapp.lccode.utils.showMessage
import com.emapp.lccode.utils.statesListall
import com.emapp.lccode.utils.toJsonStr
import com.emapp.lccode.view.ProjectDeviceTypeDialog
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.Toaster
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.ext.parseState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class ProjectMapActivity : BaseActivity1<ProjectViewModel, ActivityProjectMapBinding>(),
    AMap.OnMyLocationChangeListener, AMap.OnMarkerClickListener, AMap.OnPolylineClickListener,
    ProjectDeviceTypeDialog.SelectTypeListener, AMap.OnMapClickListener,
    GeocodeSearch.OnGeocodeSearchListener {
    private val aMap: AMap by lazy { mViewBind.mapView.map }
    var project_name = ""
    var map_Polygon = ""//项目划区json文件名
    val geocoderSearch: GeocodeSearch by lazy { GeocodeSearch(this) }
    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            titleBar(mViewBind.lvTitle.ivBar)
            statusBarDarkFont(true)
            fullScreen(true)
            statusBarColor(R.color.transparent)
            navigationBarColor(R.color.white)
        }
        AMapLocationClient.updatePrivacyShow(this, true, true)
        AMapLocationClient.updatePrivacyAgree(this, true)
        geocoderSearch.setOnGeocodeSearchListener(this)
        mViewBind.mapView.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        map_Polygon = intent.getStringExtra("map").toString()
        project_name = intent.getStringExtra("name").toString()
        mViewModel.project_id = intent.getStringExtra("id").toString()
        mViewBind.lvTitle.tvTitle.text = "项目"
        mViewBind.lvTitle.tvRight.visibility = View.GONE
        mViewBind.tvSearch.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                mViewModel.keywords = v.text.toString().trim()
                mViewModel.getDevice()
                true
            } else {
                false
            }
        }
        if (!SettingUtil.isLocationEnabled(this)) {
            showMessage(
                "手机定位服务未打开！",
                "温馨提示",
                "去开启",
                positiveAction = {
                    val settingsIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    startActivity(settingsIntent)
                })
        }
        getPermission()
    }

    private fun getPermission() {
        XXPermissions.with(this)
            .permission(Permission.ACCESS_COARSE_LOCATION)
            .permission(Permission.ACCESS_FINE_LOCATION)
            .permission(Permission.READ_PHONE_STATE)
            .permission(Permission.MANAGE_EXTERNAL_STORAGE)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    MmkvUtil.putBoolean("loc_permission", true)
                    setUpMapIfNeeded()
                    mViewModel.jsonMap(map_Polygon)
                    mViewModel.getDevice()
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {}
            })
    }

    override fun createObserver() {
        mViewModel.run {
            map_project.observe(this@ProjectMapActivity) {
                if (it?.features != null) {
                    viewModelScope.launch {
                        withContext(Dispatchers.IO) {
                            it.features?.forEach { feature ->
                                if (feature?.geometry != null) {
                                    val lat: ArrayList<LatLng> = arrayListOf()
                                    when (feature.geometry.type) {
                                        "Polygon", "MultiLineString" -> {
                                            val d =
                                                feature.geometry.coordinates as? ArrayList<ArrayList<ArrayList<Double>>>
                                            d?.forEach { c ->
                                                lat.clear()
                                                c.forEach { e ->
                                                    lat.add(
                                                        MapAppUtil.other2Gao(
                                                            this@ProjectMapActivity,
                                                            LatLng(e[1], e[0])
                                                        )
                                                    )
                                                }
                                                lat.removeAt(0)
                                                addPolygon(lat)
                                            }
                                        }

                                        "MultiPolygon" -> {
                                            val d =
                                                feature.geometry.coordinates as? ArrayList<ArrayList<ArrayList<ArrayList<Double>>>>
                                            d?.forEach { c ->
                                                c.forEach { e ->
                                                    lat.clear()
                                                    e.forEach { f ->
                                                        lat.add(
                                                            MapAppUtil.other2Gao(
                                                                this@ProjectMapActivity,
                                                                LatLng(f[1], f[0])
                                                            )
                                                        )
                                                    }
                                                    lat.removeAt(0)
                                                    // 绘制一个长方形
                                                    addPolygon(lat)
                                                }
                                            }

                                        }

                                        "LineString" -> {
                                            val d =
                                                feature.geometry.coordinates as? ArrayList<ArrayList<Double>>
                                            lat.clear()
                                            d?.forEach { c ->
                                                lat.add(
                                                    MapAppUtil.other2Gao(
                                                        this@ProjectMapActivity,
                                                        LatLng(c[1], c[0])
                                                    )
                                                )
                                                addPolygon(lat)
                                            }
                                        }

                                        else -> {
                                            log_e("feature.geometry.type==" + feature.geometry.type)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            devicelist.observe(this@ProjectMapActivity) { resultState ->
                parseState(resultState, {
                    removeMarkers()
                    removePolylines()
                    polylineDataMap.clear()
                    if (it != null) {
                        viewModelScope.launch {
                            withContext(Dispatchers.IO) {
                                it.forEach { d ->
                                    if (!d.lat.isNullOrBlank() && !d.lng.isNullOrBlank() && d.lat?.toDoubleOrNull() != null && d.json_text.isNullOrBlank()) {
                                        addMarker(d)
                                    }
                                    if (d.lu != null) {
                                        d.lu!!.features?.forEach { features ->
                                            val geometry = features.geometry
                                            if (geometry != null) {
                                                var lat: ArrayList<LatLng> = arrayListOf()
                                                when (geometry.type) {
                                                    "LineString" -> {
                                                        lat.clear()
                                                        val data =
                                                            geometry.coordinates as? ArrayList<ArrayList<Double>>
                                                        data?.forEach { c ->
                                                            lat.add(
                                                                MapAppUtil.other2Gao(
                                                                    this@ProjectMapActivity,
                                                                    LatLng(c[1], c[0])
                                                                )
                                                            )
                                                        }
                                                        addPolyline(lat, d)
                                                    }

                                                    "Polygon", "MultiLineString" -> {
                                                        val data =
                                                            geometry.coordinates as? ArrayList<ArrayList<ArrayList<Double>>>
                                                        data?.forEach { c ->
                                                            lat.clear()
                                                            c.forEach { cc ->
                                                                lat.add(
                                                                    MapAppUtil.other2Gao(
                                                                        this@ProjectMapActivity,
                                                                        LatLng(cc[1], cc[0])
                                                                    )
                                                                )
                                                            }
                                                            addPolyline(lat, d)
                                                        }
                                                    }

                                                    "MultiPolygon" -> {
                                                        val data =
                                                            geometry.coordinates as? ArrayList<ArrayList<ArrayList<ArrayList<Double>>>>
                                                        data?.forEach { c ->
                                                            c.forEach { cc ->
                                                                lat.clear()
                                                                cc.forEach { ccc ->
                                                                    lat.add(
                                                                        MapAppUtil.other2Gao(
                                                                            this@ProjectMapActivity,
                                                                            LatLng(ccc[1], ccc[0])
                                                                        )
                                                                    )
                                                                }
                                                                addPolyline(lat, d)
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }, {
                    Toaster.show(it.errorMsg)
                })
            }
        }
    }

    /**
     * 绘制项目区域
     */
    suspend fun addPolygon(lat: ArrayList<LatLng>) {
        val pOption =
            PolygonOptions().addAll(lat).strokeWidth(4f)
                .strokeColor(Color.argb(50, 1, 1, 1))
                .fillColor(Color.argb(30, 253, 1, 1))
        withContext(Dispatchers.Main) {
            mViewModel.polygons.add(aMap.addPolygon(pOption))
        }
    }

    /**
     * 绘制设备路线
     */
    private suspend fun addPolyline(lat: ArrayList<LatLng>, device: DeviceKt) {
        var draw = R.drawable.map_l_guan
        draw = getLuByNameState(
            device.work_type,
            device.title,
            device.build_status
        )
        val poly = PolylineOptions()
            .addAll(lat)
            .width(14f)
            .setCustomTexture(
                BitmapDescriptorFactory.fromResource(
                    draw
                )
            )
        withContext(Dispatchers.Main) {
            mViewModel.polylines.add(aMap.addPolyline(
                poly
            ).apply {
                mViewModel.polylineDataMap[id] = device
            })
        }
    }

    /**
     * 绘制设备路线
     */
    suspend fun addMarker(device: DeviceKt) {
        val mark = MarkerOptions().anchor(0.5f, 1.0f)
            .snippet(device.title)
            .position(
                LatLng(
                    device.lat!!.toDouble(),
                    device.lng!!.toDouble()
                )
            )
        if (device.iconthumb.isNullOrEmpty() || device.iconthumb == "null" || device.iconthumb == "0") {
            mark.icon(
                BitmapDescriptorFactory.fromBitmap(
                    scaleBitmap(
                        BitmapDescriptorFactory.fromResource(
                            getIconByNameState(
                                device.work_type,
                                device.title,
                                device.build_status
                            )
                        ).bitmap, 1.4f
                    )
                )
            )
            withContext(Dispatchers.Main) {
                mViewModel.markers.offer(aMap.addMarker(
                    mark
                ).apply { `object` = device })
            }
        } else {
            val url=if (device.iconthumb.startsWith("http")) device.iconthumb else BaseConfig.ROOT_URL+device.iconthumb
            Glide.with(this).asBitmap().load(url)
                .into(object : SimpleTarget<Bitmap>(50, 50) {
                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?,
                    ) {
                        mark.icon(BitmapDescriptorFactory.fromBitmap(resource))
                        mViewModel.markers.offer(aMap.addMarker(
                            mark
                        ).apply { `object` = device })

                    }
                })
        }

//        withContext(Dispatchers.Main) {
//            mViewModel.markers.add(aMap.addMarker(
//                mark
//            ).apply { `object` = device })
//        }

    }

    private fun setUpMapIfNeeded() {
        aMap.apply {
            isMyLocationEnabled = true
            setOnMyLocationChangeListener(this@ProjectMapActivity)
            setOnMapClickListener(this@ProjectMapActivity)
            moveCamera(CameraUpdateFactory.zoomTo(15f))
            mapType = AMap.MAP_TYPE_SATELLITE // 卫星地图模式
            uiSettings.isZoomControlsEnabled = false
            uiSettings.isRotateGesturesEnabled = false
            uiSettings.isMyLocationButtonEnabled = false // 设置默认定位按钮是否显示
            setOnMarkerClickListener(this@ProjectMapActivity)
            setOnPolylineClickListener(this@ProjectMapActivity)
            myLocationStyle = MapAppUtil.setupLocationStyle(5)
        }
    }


    override fun onMyLocationChange(location: Location?) {
        if (location == null) {
            Toaster.show("定位失败，请检查您的定位权限")
            return
        }
        if (location.latitude == 0.0)
            return
        mViewModel.mylocation = location
        if (mViewModel.isRecordLine) {
            LatLng(location.latitude, location.longitude).run {
                if (!mViewModel.guiji.contains(this)) {
                    mViewModel.guiji.add(this)
                    addLine()
                }
            }

        }
        if (mViewModel.isFirstLoc && location.latitude > 0) {
            aMap.moveCamera(
                CameraUpdateFactory.newLatLng(
                    LatLng(
                        location.latitude,
                        location.longitude
                    )
                )
            )
            mViewModel.isFirstLoc = false
        }

    }

    /**
     * 录制轨迹
     */
    private fun addLine() {
        mViewModel.removeLine()
        val poly = PolylineOptions()
            .addAll(mViewModel.guiji)
            .width(12f)
            .color(Color.RED)
        //.setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.map_l_guan))
        mViewModel.polyline = aMap.addPolyline(poly)
    }

    override fun onMarkerClick(p0: Marker?): Boolean {
        val device: DeviceKt = p0?.`object` as DeviceKt
        if (device != null) {
            showInfo(device)
        }
        return true
    }

    @SuppressLint("NewApi")
    override fun onPolylineClick(p0: Polyline?) {
        log_e("onPolylineClick---------" + p0?.id)
        log_e("onPolylineClick----polylineDataMap-----" + mViewModel.polylineDataMap.toString())
        val device: DeviceKt? = mViewModel.polylineDataMap[p0?.id]
        if (device != null) {
            showInfo(device)
        } else {
            log_e("onPolylineClick-------device=null--")
        }
    }

    private fun showInfo(device: DeviceKt) {
        MaterialDialog(this).show {
            lifecycleOwner(this@ProjectMapActivity)
            customView(R.layout.dialog_map_project_device)
            val name = getCustomView().findViewById<TextView>(R.id.tv_name)
            val tv_add = getCustomView().findViewById<TextView>(R.id.tv_add)
            val tv_progress = getCustomView().findViewById<TextView>(R.id.tv_progress)
            val tv_info = getCustomView().findViewById<TextView>(R.id.tv_info)
            name.text = device.name
            device.projectname = project_name
            if (device.build_status == "3") {
                tv_add.text = "已竣工"
                tv_add.setBackgroundResource(R.drawable.bg_bt_gray2)
            } else {
                tv_add.text = "工程上报"
                tv_add.setBackgroundResource(R.drawable.bg_bt_green2)
                tv_add.setOnClickListener {
                    cancel()

                    //EventBus.getDefault().postSticky(EventBusModel(EventBusConfig.PROJECT_DEVICE,device))
                    val intent = Intent(this@ProjectMapActivity, ProjectReportActivity::class.java)
                    intent.putExtra("flag", "create")
                    intent.putExtra("device_id", device.id)
                    intent.putExtra("device_name", device.name)
                    intent.putExtra("create_time", device.star_time)
                    intent.putExtra("project_id", mViewModel.project_id)
                    intent.putExtra("project_name", project_name)
//                    intent.putExtra("infor1", device)
//                    intent.putExtra("infor2", device)
//                    intent.putExtra("infor3", device)
                    MmkvUtil.putString("infor1", device.toJsonStr())
//                    MmkvUtil.putString("infor2",device.toJsonStr())
//                    MmkvUtil.putString("infor3",device.toJsonStr())
                    startActivity(intent)
                }
            }
            tv_progress.setOnClickListener {
                cancel()
                val intent = Intent(this@ProjectMapActivity, ProgressListActivity::class.java)
//                intent.putExtra("infor", device)
                MmkvUtil.putString("infor", device.toJsonStr())
                intent.putExtra("project_id", mViewModel.project_id)
                intent.putExtra("project_name", project_name)
                startActivity(intent)
            }
            tv_info.setOnClickListener {
                cancel()
                val intent = Intent(this@ProjectMapActivity, ProjectAddKtActivity::class.java)
                intent.putExtra("flag", "edit")
//                intent.putExtra("infor", device)
//                intent.putExtra("json_text", device.json_text)
                MmkvUtil.putString("infor", device.toJsonStr())
                MmkvUtil.putString("json_text", device.json_text)
                intent.putExtra("project_id", mViewModel.project_id)
                intent.putExtra("project_name", project_name)
                startActivity(intent)
            }
        }
    }

    @SuppressLint("CheckResult")
    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mViewBind.lvTitle.ivLeft,
            mViewBind.lvTitle.tvRight,
            mViewBind.ivL,
            mViewBind.tvAdd,
            mViewBind.ivStart,
            mViewBind.ivEnd,
            mViewBind.ivDelete,
            mViewBind.tvType,
            mViewBind.tvState,
            mViewBind.btSearch,
            mViewBind.ivLoc
        ) {
            when (it.id) {
                R.id.iv_l, R.id.iv_left -> {
                    finish()
                }

                R.id.tv_type -> {
                    mViewModel.typeDialog.listener = this
                    mViewModel.typeDialog.project_id = mViewModel.project_id
                    mViewModel.typeDialog.selectType = mViewModel.selectType
                    mViewModel.typeDialog.show(this)
                }

                R.id.tv_state -> {
                    MaterialDialog(this).show {
                        cancelable(true)
                        lifecycleOwner(this@ProjectMapActivity)
                        listItems(null, statesListall) { v, index, text ->
                            mViewBind.tvState.text = text
                            mViewModel.build_status = when (text) {
                                "未开工" -> "1"
                                "建设中" -> "2"
                                "已竣工" -> "3"
                                "全部" -> ""
                                else -> {
                                    ""
                                }
                            }
                            mViewModel.getDevice()
                            //infor.build_status = if (text == "未开工") "1" else "2"
                        }
                    }
                }

                R.id.bt_search -> {
                    mViewModel.keywords = mViewBind.tvSearch.text.toString()
                    mViewModel.getDevice()
                }

                R.id.iv_loc -> {
                    if (mViewModel.mylocation != null && mViewModel.mylocation!!.latitude > 0) {
                        aMap.moveCamera(
                            CameraUpdateFactory.newLatLngZoom(
                                LatLng(
                                    mViewModel.mylocation!!.latitude,
                                    mViewModel.mylocation!!.longitude
                                ), 15f
                            )
                        )
                    }

//                    MaterialDialog(this@ProjectMapActivity).show {
//                        lifecycleOwner(this@ProjectMapActivity)
//                        customView(R.layout.dialog_pro_device)
//                        var name = getCustomView().findViewById<TextView>(R.id.tv_name)
//                        name.text = "测试"
//
//                    }
                }

                R.id.tv_add -> {
                    var latLng = if (mViewModel.mylocation != null)
                        LatLng(
                            mViewModel.mylocation?.latitude!!,
                            mViewModel.mylocation?.longitude!!
                        ) else null
                    if (!BaseConfig.isDebug)
                        if (latLng == null || !inProjectAir(latLng)) {
                            showMessage("当前位置不在项目范围内！")
                            return@setOnclickNoRepeat
                        }
                    MaterialDialog(this@ProjectMapActivity).show {
                        lifecycleOwner(this@ProjectMapActivity)
                        customView(R.layout.dialog_pro_add)
                        var loc = getCustomView().findViewById<TextView>(R.id.tv_loc)
                        var gui = getCustomView().findViewById<TextView>(R.id.tv_guiji)
                        loc.setOnClickListener {
                            cancel()
                            val intent =
                                Intent(this@ProjectMapActivity, ProjectAddKtActivity::class.java)
                            intent.putExtra("flag", "create")
                            intent.putExtra("project_id", mViewModel.project_id)
                            intent.putExtra("project_name", project_name)
//                            intent.putExtra("json_text", "")
                            MmkvUtil.putString("json_text", "")
                            startActivity(intent)
//                            if (mViewModel.mylocation == null) {
//                                Toaster.show("定位失败！")
//                                return@setOnClickListener
//                            }
//                            var point = LatLonPoint(
//                                mViewModel.mylocation!!.latitude,
//                                mViewModel.mylocation!!.longitude
//                            )
//                            showLoading("定位中...")
//                            getAddress(point)
                        }
                        gui.setOnClickListener {
                            cancel()
                            mViewBind.run {
                                tvAdd.visibility = View.GONE
                                fvStart.visibility = View.VISIBLE
                                ivStart.visibility = View.VISIBLE
                                ivEnd.visibility = View.GONE
                                ivDelete.visibility = View.VISIBLE
                            }

                        }
                    }
                }

                R.id.iv_start -> {
                    mViewBind.run {
                        tvAdd.visibility = View.GONE
                        fvStart.visibility = View.VISIBLE
                        ivStart.visibility = View.GONE
                        ivEnd.visibility = View.VISIBLE
                        ivDelete.visibility = View.GONE
                    }

                    mViewModel.run {
                        guiji.clear()
                        isRecordLine = true
                        removeLine()
                    }
                }

                R.id.iv_end -> {
                    mViewBind.run {
                        tvAdd.visibility = View.VISIBLE
                        fvStart.visibility = View.GONE
                    }
                    mViewModel.isRecordLine = false
                    val gson = getluJsonString(mViewModel.guiji)
                    val intent =
                        Intent(this@ProjectMapActivity, ProjectAddKtActivity::class.java)
                    intent.putExtra("flag", "create")
                    //intent.putExtra("json_text", gson)
                    MmkvUtil.putString("json_text", gson)
                    intent.putExtra("project_id", mViewModel.project_id)
                    intent.putExtra("project_name", project_name)
                    startActivity(intent)

                }

                R.id.iv_delete -> {
                    mViewBind.run {
                        tvAdd.visibility = View.VISIBLE
                        fvStart.visibility = View.GONE
                    }
                    mViewModel.removeLine()
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: EventBusModel) {
        when (event.type) {
            EventBusConfig.REFRESH_PROJECT_DEVICE -> {
                mViewModel.getDevice()
            }

            else -> {}
        }
    }

    override fun onSelectTypeComplete(type: SelectType) {
        mViewModel.selectType = type
        mViewModel.device_type = type.device_type
        var t = type.name0
        if (!type.device_type_name.isNullOrBlank())
            t = "$t,${type.device_type_name}"
        mViewBind.tvType.text = t
        mViewModel.getDevice()
    }

    override fun onResume() {
        super.onResume()
        mViewBind.mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mViewBind.mapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mViewBind.mapView.onSaveInstanceState(outState)
    }

    override fun onDestroy() {
        super.onDestroy()
        mViewBind.mapView.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onMapClick(p0: LatLng?) {

    }

    fun inProjectAir(p0: LatLng): Boolean {
        var have = false
        for (p in mViewModel.polygons) {
            if (p.contains(p0)) {
                have = true
                break
            }
        }
        return have
    }

    override fun onRegeocodeSearched(result: RegeocodeResult?, resultCode: Int) {
        dismissLoading()
        if (resultCode == AMapException.CODE_AMAP_SUCCESS && result != null) {
            val address = result.regeocodeAddress?.formatAddress
            val latlng = UpLatLngKt(
                mViewModel.mylocation!!.longitude,
                mViewModel.mylocation!!.latitude,
                address
            )
        } else {
            Toaster.show("定位失败")
        }
    }

    override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {
    }

}